
import { ManualSampleParams, OverallMode, SampleMethodProps, SampleParameterValues, ProjectOverallProps, SampleStepInfo, WhereSqlParams } from "@/pages/auditSampling/typing";
import { forwardRef, useContext, useRef, useState } from "react";
import { Button, NumberBox } from "devextreme-react";
import { consts } from "@/pages/auditSampling/consts";
import { getSampleListByWhereSql, getSampleSizeAndAmount, getTextFieldsValues, getToBeTestWhereSql, getWhereSqlBySampleList } from "../NonStatSampleService";
import { SampleStepInfoContext } from "../../samplingRecordPopup";
import { ClickEvent } from "devextreme/ui/button";
import { getSampleOverallWhereSQL, iniFormQueryAndAdvParams } from "../../samplingProjectOverallService";
import { ViewSampleListPopup } from "../ViewSampleListPopup";

export const ManualSample = forwardRef((props: SampleMethodProps, ref: any) => {
    //上级传入的抽样参数
    const sampleStepInfo: SampleStepInfo = useContext(SampleStepInfoContext);
    const { sampleParameterValues, setSampleParameterValues } = props;
    const nonStatSampleParameter: SampleParameterValues = sampleParameterValues;

    const viewSampleListPopupRef = useRef<any>();
    const [isNeedViewSampleListPopup, setIsNeedViewSampleListPopup] = useState<boolean>(false);
    //特殊样本
    function selectMunualSampleListPopup(e: ClickEvent): void {
        setIsNeedViewSampleListPopup(true)
        //重新获取一个新的projectOverallProps,把所有的方法都干掉,不能影响原来的
        const projectOverallProps = sampleStepInfo.projectOverallProps ? JSON.parse(JSON.stringify(sampleStepInfo.projectOverallProps)) : {};
        const sampleWhereSQL = getSampleOverallWhereSQL(projectOverallProps?.curWhereSqlParams as WhereSqlParams)
        projectOverallProps.overallMode = OverallMode.select;
        projectOverallProps.fixedWhereSql = sampleWhereSQL + getToBeTestWhereSql(nonStatSampleParameter);
        const interval = setInterval(async () => {
            if (viewSampleListPopupRef.current) {
                clearInterval(interval)
                const manualSampleParams = nonStatSampleParameter.manualSampleParams as ManualSampleParams
                const manualWhereSql = manualSampleParams.manualWhereSql;
                const sampledList = manualWhereSql ? await getSampleListByWhereSql(sampleStepInfo, manualWhereSql) : []
                const textFieldsArray = projectOverallProps?.curSampleTable?.sampleTextFieldsArray || [];
                const numFieldsArray = projectOverallProps?.curSampleTable?.sampleNumFieldsArray || [];

                iniFormQueryAndAdvParams(projectOverallProps);

                viewSampleListPopupRef.current.show({
                    title: '请选择样本',
                    sampleProjectOverallProps: projectOverallProps,
                    specialSampleList: sampledList,//nonStatSampleParameter.specialSampleList || [],
                    setIsNeedViewSampleListPopup: setIsNeedViewSampleListPopup,
                    okCallback: async (allSampledList: any[]) => {//allSampledList表示新旧都有
                        let manualWhereSql = '';
                        let sampledAmountSum = 0;
                        if (allSampledList.length == 0) {
                            manualWhereSql = '';
                        } else {
                            manualWhereSql = await  getWhereSqlBySampleList(sampleStepInfo, allSampledList)
                            allSampledList.forEach(item => {
                                let amount = 0;
                                numFieldsArray.forEach((fieldName: string) => { amount += item[fieldName] || 0 })
                                sampledAmountSum += amount
                            })
                        }

                        const sampledList = allSampledList
                        const sampledSize = sampledList.length; //newSpecialSampleList.length;
                        const sampleTextFieldValues = allSampledList.map(item => getTextFieldsValues(item, textFieldsArray));
                        nonStatSampleParameter.manualSampleParams = { manualWhereSql, sampledList, sampledSize, sampledAmountSum, sampleTextFieldValues }


                        nonStatSampleParameter.sampledResult = { sampledList, sampledSize, sampledAmountSum, sampleTextFieldValues }

                        const sampleSizeAndAmount = await getSampleSizeAndAmount(sampleStepInfo, sampleParameterValues.toBeTestWhereSql);
                        nonStatSampleParameter.sampledResult.sampledNumFields = { ...sampleSizeAndAmount.sampledNumFields };

                        setSampleParameterValues({ ...nonStatSampleParameter });
                        setIsNeedViewSampleListPopup(false)
                    }
                })
            }
        }, 10);

    }

    return <div className="itemBoxDispalyLeft"
        style={{ marginLeft: 0, height: 125, border: '1px solid #e5e5e5', borderRadius: 5, width: '100%', alignItems: 'center' }}    >
        {/* 选择样本 */}
        {isNeedViewSampleListPopup && <ViewSampleListPopup ref={viewSampleListPopupRef} />}
        <div style={{ marginLeft: 10 }}>
            <Button text={`选择样本`} icon='fieldchooser' type="default"
                style={{ marginTop: 0 }} height={35}
                onClick={selectMunualSampleListPopup}
            />

            {/**其他内容 */}
        </div>
        <div>
            <div className="itemBoxDispalyLeft" style={{ marginLeft: 10, marginTop: 3 }}>
                <div style={{ width: 100, marginTop: 5 }}>已选样本数量：</div>
                <NumberBox readOnly={true} style={{ width: 120 }}
                    value={(nonStatSampleParameter.manualSampleParams?.sampledSize || 0)}
                />
                <div style={{ width: 100, marginTop: 5, marginLeft: 10 }}>已选样本金额：</div>
                <NumberBox readOnly={true} style={{ width: 120 }} format={consts.numberFormat}
                    value={(nonStatSampleParameter.manualSampleParams?.sampledAmountSum || 0)}
                />
            </div>
        </div>
    </div>
})